package com.aliyun.gts.sso.context;

import com.aliyun.gts.sso.constant.SFSSOLoginConstants;
import com.aliyun.gts.sso.domain.LoginAccount;
import com.aliyun.gts.sso.domain.LoginInfo;
import com.aliyun.gts.sso.domain.LoginStatus;
import jakarta.servlet.http.Cookie;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

//import javax.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Arrays;

/**
 * Created by 鸿度 on 2024-06-18 09:05.
 */
@Slf4j
public class SFLoginAccountContext {

    private static HttpServletRequest currentRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return requestAttributes instanceof ServletRequestAttributes ? ((ServletRequestAttributes) requestAttributes).getRequest() : null;
    }

    //    public static LoginAccount getLoginAccount() {
    public static LoginInfo getLoginInfo() {
        HttpServletRequest request = currentRequest();
        if (request == null) {
            return null;
        }

        Integer status = (Integer) request.getAttribute(SFSSOLoginConstants.REQUEST_ATTR_LOGIN_STATUS_INFO);
        LoginStatus loginStatus = new LoginStatus();
        loginStatus.setLoginStatus(status);

        if (status == 200) {
            Object obj = request.getAttribute(SFSSOLoginConstants.REQUEST_ATTR_LOGIN_ACCOUNT_INFO);
            //获取cookie
            Cookie[] cookies = request.getCookies();
            String result = null;
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    result = cookie.getName() + "=" + cookie.getValue();
                }
            }
            LoginInfo loginInfo = new LoginInfo();
            loginInfo.setLoginStatus(loginStatus);
            LoginAccount loginAccount = (LoginAccount) obj;
            if (obj != null) {
                loginAccount.setCookie(result);
                loginInfo.setLoginAccount(loginAccount);
            }
            return loginInfo;
        } else {
            LoginInfo loginInfo = new LoginInfo();
            loginInfo.setLoginStatus(loginStatus);
            return loginInfo;
        }
    }

}
